package controller;


import com.sun.deploy.util.StringUtils;
import db.PhoneDB;
import entity.Phone;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

//添加到购物车
@WebServlet("/cartPhoneServlet")
public class cartPhoneServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String idstr = request.getParameter("id");
        int id = Integer.parseInt(idstr);
        List<Phone> pd = PhoneDB.getAll();
        Phone sj = pd.get(id-1);
        HttpSession session = request.getSession();
        List<Phone> cart = (ArrayList<Phone>) session.getAttribute("cart");
        if(cart == null){
            cart = new ArrayList<Phone>();
        }
        cart.add(sj);
        session.setAttribute("cart",cart);
        out.println("<h2> 购物车添加成功</h2>");
        out.println("<a href=\"phoneList\"> 继续添加购物车</a> <br>");
        out.println("<a href=\"ListCartServlet\"> 查看购物车</a>");
    }
}
